package com.zbkj.crmeb.store.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.store.dao.StoreModuleSetUpDao;
import com.zbkj.crmeb.store.model.StoreModuleSetUp;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductActive;
import com.zbkj.crmeb.store.request.StoreModuleSetUpRequest;
import com.zbkj.crmeb.store.response.StoreModuleSetUpResponse;
import com.zbkj.crmeb.store.service.ChannelStoreBrandConfigService;
import com.zbkj.crmeb.store.service.StoreModuleSetUpService;
import com.zbkj.crmeb.store.service.StoreProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class StoreModuleSetUpServiceImpl extends ServiceImpl<StoreModuleSetUpDao, StoreModuleSetUp> implements StoreModuleSetUpService {
    @Resource
    private StoreModuleSetUpDao StoreModuleSetUpDao;
    @Autowired
    ChannelStoreBrandConfigService channelStoreBrandConfigService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    private ProductConvertUtil productConvertUtil;

    /**
     * 列表
     * @Description:
     * @author duyb
     * @return CommonResult<Object>
     * @Date: 2022-10-27
     */
    @Override
    public List<StoreModuleSetUpResponse> getList() {
        //获取启用的模块
        List<StoreModuleSetUp> storeModuleSetUpList = this.list(Wrappers.<StoreModuleSetUp>lambdaQuery()
                .eq(StoreModuleSetUp::getIsShow, true)
                .orderByAsc(StoreModuleSetUp::getSort)
                .orderByAsc(StoreModuleSetUp::getCreateTime));
        List<StoreModuleSetUpResponse> storeModuleSetUpResponseList=new ArrayList<>();
        //注入商品列表
        if (CollectionUtils.isNotEmpty(storeModuleSetUpList)){
            for (StoreModuleSetUp storeModuleSetUp : storeModuleSetUpList) {
                StoreModuleSetUpResponse storeModuleSetUpResponse = new StoreModuleSetUpResponse();
                BeanUtils.copyProperties(storeModuleSetUp, storeModuleSetUpResponse);
                List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                        .in(StoreProduct::getId, JSONArray.parseArray(storeModuleSetUp.getProductIds(), Integer.class))
                        .last("limit 6")
                );
                //匹配商品图片
                productConvertUtil.convertProductImage(productList);
                storeModuleSetUpResponse.setProductList(productList);
                storeModuleSetUpResponseList.add(storeModuleSetUpResponse);
            }
        }
        return storeModuleSetUpResponseList;
    }

    /**
     * 分页查询
     * @Description:
     * @author duyb
     * @param @param [StoreModuleSetUpRequest PageParamRequest]
     * @return PageInfo<StoreModuleSetUpResponse>
     * @Date: 2022-10-27
     */
    @Override
    public PageInfo<StoreModuleSetUpResponse> pageEntity(StoreModuleSetUpRequest request, PageParamRequest pageParamRequest) {
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //组装查询条件
        LambdaQueryWrapper<StoreModuleSetUp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(request.getModuleName())){
            lambdaQueryWrapper.like(StoreModuleSetUp::getModuleName,request.getModuleName());
        }
        if (request.getType()!=null){
            lambdaQueryWrapper.eq(StoreModuleSetUp::getType,request.getType());
        }
        lambdaQueryWrapper.orderByAsc(StoreModuleSetUp::getSort);
        lambdaQueryWrapper.orderByAsc(StoreModuleSetUp::getCreateTime);
        List<StoreModuleSetUp> storeModuleSetUpList = this.list(lambdaQueryWrapper);
        List<StoreModuleSetUpResponse> storeModuleSetUpResponseList=new ArrayList<>();
        //获取模块商品数量
        if (CollectionUtils.isNotEmpty(storeModuleSetUpList)){
            for (StoreModuleSetUp storeModuleSetUp : storeModuleSetUpList) {
                StoreModuleSetUpResponse storeModuleSetUpResponse = new StoreModuleSetUpResponse();
                BeanUtils.copyProperties(storeModuleSetUp, storeModuleSetUpResponse);
                storeModuleSetUpResponse.setProductIds(JSONArray.parseArray(storeModuleSetUp.getProductIds(), Integer.class));
                storeModuleSetUpResponse.setProductNumber(JSONArray.parseArray(storeModuleSetUp.getProductIds(), Integer.class).size());
                storeModuleSetUpResponseList.add(storeModuleSetUpResponse);
            };
        }

        return  CommonPage.copyPageInfo(page, storeModuleSetUpResponseList);
    }

    /**
     * 去除下架商品
     * @Description:
     * @author duyb
     * @param @param id
     * @return Boolean
     * @Date: 2022-10-27
     */
    @Override
    public Boolean screenProduct(Integer id) {
        StoreModuleSetUp storeModuleSetUp = this.getById(id);
        //获取商品中还在上架的商品
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                .in(StoreProduct::getId, JSONArray.parseArray(storeModuleSetUp.getProductIds(), Integer.class))
                .eq(StoreProduct::getIsShow,1)
        );
        List<Integer> productIdlist = productList.stream().map(StoreProduct::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(productIdlist)){
            storeModuleSetUp.setProductIds(productIdlist.toString());
        }else {
            storeModuleSetUp.setProductIds("[]");
        }

        return  this.saveOrUpdate(storeModuleSetUp);
    }


    /**
     * 通过主键查询
     * @Description:
     * @author duyb
     * @param @param id
     * @return StoreModuleSetUpResponse
     * @Date: 2022-10-27
     */
    @Override
    public StoreModuleSetUpResponse getEntity(Integer id) {
        StoreModuleSetUp storeModuleSetUp = this.getById(id);
        StoreModuleSetUpResponse storeModuleSetUpResponse = new StoreModuleSetUpResponse();
        BeanUtils.copyProperties(storeModuleSetUp, storeModuleSetUpResponse);
        storeModuleSetUpResponse.setProductIds(JSONArray.parseArray(storeModuleSetUp.getProductIds(), Integer.class));
        //注入商品分页数据
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                .in(StoreProduct::getId, JSONArray.parseArray(storeModuleSetUp.getProductIds(), Integer.class))
        );
        if (CollectionUtils.isNotEmpty(productList)){
            //匹配商品图片
            productConvertUtil.convertProductImage(productList);
            storeModuleSetUpResponse.setProductList(productList);
        }

        return storeModuleSetUpResponse;
    }

    /**
     * 保存
     * @Description:
     * @author duyb
     * @param @param StoreBannerSetUpRequest
     * @return Boolean
     * @Date: 2022-10-27
     */
    @Override
    public Boolean saveEntity(StoreModuleSetUpRequest storeModuleSetUpRequest) {
        //模块名称不能重复
        StoreModuleSetUp one = this.getOne(Wrappers.<StoreModuleSetUp>lambdaQuery()
                .eq(StoreModuleSetUp::getModuleName, storeModuleSetUpRequest.getModuleName())
                .last("limit 1")
        );
        if (ObjectUtil.isNotNull(one)&&!Objects.equals(one.getId(),storeModuleSetUpRequest.getId())){
            throw new CrmebException("模块名称已存在!");
        }
        storeModuleSetUpRequest.setUpdateTime(new Date());
        //模块最多启用21个
        out:if (storeModuleSetUpRequest.getIsShow()){
            if (ObjectUtil.isNotNull(storeModuleSetUpRequest.getId())){
                StoreModuleSetUp moduleSetUp = this.getById(storeModuleSetUpRequest.getId());
                if (moduleSetUp.getIsShow()){
                    break out;
                }
            }
            Integer number = StoreModuleSetUpDao.selectCount(Wrappers.<StoreModuleSetUp>lambdaQuery()
                    .eq(StoreModuleSetUp::getIsShow, true)
            );
            if (number==21){
                throw new CrmebException("同时最多可展示21个模块!");
            }
        }
        if (CollectionUtils.isEmpty(storeModuleSetUpRequest.getProductIds())){
            throw new CrmebException("请选择商品!");
        }
        if (StringUtils.isBlank(storeModuleSetUpRequest.getModuleName())){
            throw new CrmebException("模块名称不能为空!");
        }
        if (StringUtils.isBlank(storeModuleSetUpRequest.getImage())){
            throw new CrmebException("模板图片不能为空!");
        }
        //排序默认999
        if (storeModuleSetUpRequest.getSort()==null){
            storeModuleSetUpRequest.setSort(999);
        }else if(storeModuleSetUpRequest.getSort()>999){
            throw new CrmebException("排序号最大为999!");
        }
        if (null==storeModuleSetUpRequest.getId()){
            storeModuleSetUpRequest.setCreateTime(new Date());
        }
        StoreModuleSetUp storeModuleSetUp = new StoreModuleSetUp();
        BeanUtils.copyProperties(storeModuleSetUpRequest, storeModuleSetUp);
        storeModuleSetUp.setProductIds(storeModuleSetUpRequest.getProductIds().toString());

        return this.saveOrUpdate(storeModuleSetUp);
    }

    /**
     * 启用/禁用
     * @Description:
     * @author duyb
     * @param @param id
     * @return Boolean
     * @Date: 2022-11-08
     */
    @Override
    public Boolean enabled(Integer id,Integer status) {
        //模块最多启用21个
        if (Objects.equals(status,1)){
            Integer number = StoreModuleSetUpDao.selectCount(Wrappers.<StoreModuleSetUp>lambdaQuery()
                    .eq(StoreModuleSetUp::getIsShow, 1)
            );
            if (number==21){
                throw new CrmebException("同时最多可展示21个模块!");
            }
        }
        boolean b = this.update(Wrappers.<StoreModuleSetUp>lambdaUpdate()
                .eq(StoreModuleSetUp::getId, id)
                .set(StoreModuleSetUp::getIsShow, status)
        );

        return b;
    }
    



}
